﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ViVa.ActiveDirectory;
using System.Web.Services;
using System.Web.Script.Services;
using System.Data;

namespace ViVa_Portal.Controllers
{
    public class ADUserController : Controller
    {

        #region LaatUserZien

        public ViewResult LaatUserZien(String SamAccountName)
        {
            if (ModelState.IsValid)
            {
                var userObj = ADService.GetUserBySamAccountName(SamAccountName);

                if (userObj == null)
                {
                    return View("ZoekADUser");
                }
                else
                    return View("LaatUserZien", userObj);
            }
            else
                return View();
        }
        #endregion


        #region Zoek AD User lijst
        [HttpGet]
        public ViewResult ZoekADUser()
        {
            return View();
        }

        [HttpPost]
        public ActionResult ZoekADUser(String searchbar_menu, String searchbar_zoekuser)
        {
            if (ModelState.IsValid)
            {
                if ((searchbar_menu != "" && searchbar_menu != null) || (searchbar_zoekuser != "" && searchbar_zoekuser != null))
                {
                    if (searchbar_menu == null) { searchbar_menu = searchbar_zoekuser; }
                    var userList = ADService.GetUsers(searchbar_menu);

                    if (userList == null)
                    {
                        return View("ZoekADUser");
                    }
                        //Checks if list contains more than one Entry. If so goes direct to the Edit screen,
                        //else it shows a list to choose from.
                    else
                        if (userList.Count == 1)
                        {
                            return RedirectToAction("EditUser", "ADUser", new { SamAccountName = userList.First().SamAccountName });
                        }
                        else
                        {
                            return View("ZoekADUser", userList);
                        }
                }
            }


                return View();

        }
        #endregion



        #region EditUser
        [HttpGet]
        public ViewResult EditUser(String samAccountName)
        {
            if (ModelState.IsValid)
            {
                var userObj = ADService.GetUserBySamAccountName(samAccountName);

                if (userObj == null)
                {
                    return View("ZoekADUser");
                }
                else
                    return View("EditUser", userObj);
            }
            else
                return View();
        }

        [HttpPost]
        public ViewResult EditUser(ADEntry userObj)
        {
            if (ModelState.IsValid)
            {

                if (Request.Form.Get("action") == "DeleteMemberOf")
                {

                    if (userObj == null)
                    {
                        return View("ZoekADUser");
                    }
                    else
                    {
                        try
                        {
                            List<string> remove = new List<string>();
                            foreach (string x in Request.Form)
                            {

                                if (Request.Form.Get(x).Contains("true"))
                                {
                                    remove.Add(x);
                                }
                            }
                            ADService.RemoveGroups(remove, userObj);
                            userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                            Logging.Log(PermissionService.userName(), 0, "Rechten verwijderd voor " + userObj.Name);
                            return View("EditUser", userObj);
                        }
                        catch (Exception ex)
                        {
                            ViewData["ErrorHandling"] = ex;
                            userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                            return View("EditUser", userObj); 
                        }
                    }
                }

                if (Request.Form.Get("action") == "AddMemberOf")
                {

                    if (userObj == null)
                    {
                        return View("ZoekADUser");
                    }
                    else
                    {
                        try
                        {
                            List<string> add = new List<string>();
                            foreach (string x in Request.Form)
                            {

                                if (Request.Form.Get(x).Contains("on"))
                                {
                                    add.Add(x);
                                }
                            }
                            ADService.AddGroups(add, userObj);
                            userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                            Logging.Log(PermissionService.userName(), 0, "Rechten toegevoegd " + userObj.Name);
                            return View("EditUser", userObj);
                        }
                        catch (Exception ex)
                        {
                            ViewData["ErrorHandling"] = ex;
                            ViewBag.CustomError = "Je hebt geen schrijf rechten op dit gedeelte van het Active Directory";
                            userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                            return View("EditUser", userObj); 
                        }
                    }
                }

                if (Request.Form.Get("action") == "AccountAccessControl")
                {

                    if (userObj == null)
                    {
                        return View("ZoekADUser");
                    }
                    else

                        try
                        {
                            if (Request.Form.Get("datetime_checkbox") == "false")
                            {
                                userObj.AccountExpires = "0";
                            }
                            ADService.Save(userObj);
                            userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                            Logging.Log(PermissionService.userName(), 0, "Access Control aangepast voor " + userObj.Name + ". Lockout datum: " + userObj.AccountExpires + ". Account disabled: " + userObj.AccountDisabled.ToString());
                            return View("EditUser", userObj);
                        }
                        catch (Exception ex)
                        {
                            ViewData["ErrorHandling"] = ex;
                        }
                 }

                if (Request.Form.Get("action") == "ChangePassword")
                {
                    try
                    {
                        userObj = ADService.GetUserBySamAccountName(userObj.SamAccountName);
                        if (userObj == null)
                        {
                            return View("ZoekADUser");
                        }
                        else
                            if (Request.Form.Get("passWord").Equals(Request.Form.Get("passWord_check")))
                            {
                                ADService.ChangeUserPassword(userObj, Request.Form.Get("passWord"));
                                Logging.Log(PermissionService.userName(), 0, "Wachtwoord aangepast voor " + userObj.Name);
                                return View("EditUser", userObj);
                            } else {
                                    ViewBag.CustomError = "De opgegeven wachtwoorden komen niet overeen";
                                    return View("EditUser", userObj);
                                   }       
                    }
                    catch(Exception ex)
                    { 
                        ViewBag.ErrorHandling = ex;
                        return View("EditUser", userObj); 
                    }
                }

                return View("ZoekADUser");
            }
            else
                return View("ZoekADUser");
        }
        #endregion


        #region JQuery methodes

        [WebMethod]
        public ActionResult GetUserNames(string q)
        {
            return Content (string.Join("\n", ADService.GetUsers(q).Select(i => i.Name).ToArray()));
        }

        [WebMethod]
        public ActionResult GetUserNames_menu(string q)
        {
            return Content(string.Join("\n", ADService.GetUsers(q).Select(i => i.Name).ToArray()));
        }

        [WebMethod]
        public string GetGroups(string q)
        {
            List<ADGroup> group = ADService.GetGroups(q);
            DataSet ds = Helper.ToDataSet<ADGroup>(group);
            string result = ds.GetXml();
            return (result);

            //return Content(string.Join("\n", ADService.GetUsers(q).Select(i => i.Name).ToArray()));
             
        }

        [WebMethod]
        public void SaveADUser(string userString)
        {
            ADEntry userObj = Helper.JsonToADEntry(userString);
            ADService.Save(userObj);            
        }

        [WebMethod]
        public string getGroupsJSON(string groupString)
        {
            var groups = ADService.GetGroups(groupString, false);
            string sJSON = Helper.ToJson(groups);
            return (sJSON);
        }

        [WebMethod]
        public string getGroupsJSON2(string groupString)
        {
            var groups = ADService.GetGroupByDistinguishedName(groupString);
            string sJSON = Helper.ToJson(groups);
            ViewBag.testJSON = sJSON;
            return (sJSON);
        }

        #endregion








        public ViewResult test()
        {
            //List<string> fileList = UserProfileService.fileList();
            //return View(fileList);
            return View();
        }

        

    }
} 